package com.base.common.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Random;

import javax.imageio.ImageIO;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.base.common.GlobaConstants;
import com.base.common.bean.ActionResult;

/**
 * User: jay.zhoujingjie Date: 14-1-16 Time: 上午9:26
 */
@Action("systemAction")
@Results({
		@Result(name = "image", type = "stream", params = {
				GlobaConstants.CONTENT_TYPE, GlobaConstants.CONTENT_TYPE_JPG,
				"inputName", "inputStream" }),
		@Result(name = GlobaConstants.ASYNCHRONOUS, type = GlobaConstants.JSON, params = {
				GlobaConstants.ROOT, GlobaConstants.ACTION_RESULT }) })
public class SystemAction extends AbstractBaseAction { // 配置文件服务类
	private Integer width; // 验证码宽度
	private Integer height; // 验证码高度
	private char[] str = "123456789qwertyuipasdfghjklzxcvbnm".toCharArray(); // 验证码最近出现的字符，已去掉0和o
	private InputStream inputStream;
	private String validateCode;

	public String getValidateCode() {
		return validateCode;
	}

	public void setValidateCode(String validateCode) {
		this.validateCode = validateCode;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public Integer getWidth() {
		return width;
	}

	public void setWidth(Integer width) {
		this.width = width;
	}

	public Integer getHeight() {
		return height;
	}

	public void setHeight(Integer height) {
		this.height = height;
	}

	/**
	 * 创建随机函数随机出现四位验证码
	 * 
	 * @return String
	 */
	private String generateCode(Integer length, Graphics g) {
		Date date = new Date();
		date.toString();
		// 得到随机产生的验证码数字。
		StringBuilder code = new StringBuilder();
		Random random = new Random();
		for (int i = 0; i < length; i++) {
			char rand = str[random.nextInt(str.length - 1)];
			// 产生随机的颜色分量来构造颜色值，这样输出的每位数字的颜色值都将不同。

			int red = random.nextInt(255);
			int green = random.nextInt(165);
			int blue = random.nextInt(1);
			// 用随机产生的颜色将验证码绘制到图像中。
			g.setColor(new Color(red, green, blue));
			g.drawString(String.valueOf(rand), (i + 1) * (width - 4)
					/ (length + 1), height - 7);
			// 将产生的四个随机数组合在一起。
			code.append(rand);
		}
		return code.toString();
	}

	/**
	 * 生成干扰点
	 */
	private void generateSpot(Graphics graphics) {
		Random random = new Random();
		for (int i = 0; i < 250; i++) {
			int x = (int) (Math.random() * width);
			int y = (int) (Math.random() * height);
			graphics.setColor(new Color(random.nextInt(255), random
					.nextInt(255), random.nextInt(255)));
			graphics.drawOval(x, y, 1, 0);
		}
	}

	/**
	 * 生成图
	 * 
	 * @param g
	 * @return
	 */
	private Graphics generateGraphics(Graphics g) {
		// 将图形填充为白色
		g.setColor(Color.LIGHT_GRAY);
		g.fillRect(0, 0, width, height);
		// 创建字体，字体的大小应该根据图片的高度来定。
		g.setFont(new Font("Fixedsys", Font.PLAIN, height - 10));
		// 画边框。
		g.setColor(Color.WHITE);
		g.drawRect(0, 0, width - 1, height - 1);
		return g;
	}

	/**
	 * 验证码
	 * 
	 * @return
	 */
	public String validateCode() throws IOException {

		if (width == null) {
			width = 87;
		}
		if (height == null) {
			height = 37;
		}
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		// 生成图
		Graphics g = generateGraphics(image.getGraphics());
		// 随机产生干扰点，使图象中的认证码不易被其它程序探测到。
		generateSpot(g);
		// randomCode用于保存随机产生的验证码，以便用户登录后进行验证。
		String randCode = generateCode(4, g);

		// 禁止图像缓存。
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		// 将图像输出到Servlet输出流中。
		ByteArrayOutputStream sos = new ByteArrayOutputStream();
		ImageIO.write(image, "jpeg", sos);
		inputStream = new ByteArrayInputStream(sos.toByteArray());
		sos.close();
		// 将四位数字的验证码保存到Session中。
		session.put("checkCode", randCode);
		return "image";
	}

	/**
	 * 检查验证码是否正确
	 * 
	 * @return
	 */
	public String checkValidateCode() {
		actionResult = ActionResult.getActionResult(false);
		if (validateCode != null) {
			if (validateCode.equals(String.valueOf(session.get("checkCode")))) {
				actionResult = ActionResult.getActionResult(true);
			}
		}
		return GlobaConstants.ASYNCHRONOUS;
	}

	/**
	 * 注销和退出方法，作用在于清除session
	 * 
	 * @author scott.suhao
	 */
	public String logoutSys() {
		// 注销session
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.logout();
		return GlobaConstants.ASYNCHRONOUS;
	}
}
